<?php
/**
 * DBShop 电子商务系统
 *
 * ==========================================================================
 * @link      https://www.dbshop.net/
 * @copyright 北京珑大钜商科技有限公司，并保留所有权利。
 * @license   https://www.dbshop.net/license.html License
 * ==========================================================================
 *
 * @author    静静的风 <baron@loongdom.cn>
 *
 */

namespace Admin\Validator;

use Imagine\Gd\Imagine;
use Laminas\I18n\Translator\Translator;
use Laminas\Validator\AbstractValidator;

/**
 * 对上传的图片长宽进行校验，是否符合对应图片类型的上传要求，如 商品图片、品牌图片
 */
class ImageWidthOrHeightCheckValidator extends AbstractValidator
{
    const ERROR_WIDTH   = 'errorWidth';
    const ERROR_HEIGHT  = 'errorHeight';

    protected $options = [
        'defaultWidth',
        'defaultHeight'
    ];

    protected $messageTemplates = [];

    public function __construct($options = null)
    {
        $this->options['defaultWidth'] = $options['defaultWidth'] ?? 0;
        $this->options['defaultHeight']= $options['defaultHeight'] ?? 0;

        $trans = new Translator();
        $this->messageTemplates = [
            self::ERROR_WIDTH   => sprintf($trans->translate("图片宽度小于 %s，请重新上传"), $this->options['defaultWidth']),
            self::ERROR_HEIGHT  => sprintf($trans->translate("图片高度小于 %s，请重新上传"), $this->options['defaultHeight'])
        ];

        parent::__construct($options);
    }

    public function isValid($value)
    {
        if ($this->options['defaultWidth'] <= 0 || $this->options['defaultHeight'] <= 0) return true;

        try {
            $imagine = new Imagine();
            $imageSize = $imagine->open($value['tmp_name'])->getSize();

            if ($this->options['defaultWidth'] > 0 && $imageSize->getWidth() < $this->options['defaultWidth']) {
                $this->error(self::ERROR_WIDTH);
                return false;
            }

            if ($this->options['defaultHeight'] > 0 && $imageSize->getHeight() < $this->options['defaultHeight']) {
                $this->error(self::ERROR_HEIGHT);
                return false;
            }
        } catch (\Exception $e) {
            return true;
        }

        return true;
    }
}